package cn.com.generaldata.os.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorInfo;
import cn.com.generaldata.jsme_indicator_system.entity.ReportTypeIndicator;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.AreaPerform;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.vo.DynamicReportVO;
import cn.com.generaldata.os.vo.ReportIndicatorQueryVO;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 报表指标查询service.
 */
@Service
public class ReportIndicatorQueryService {

	private static final Logger logger = LoggerFactory.getLogger(ReportIndicatorQueryService.class);

	private static final String AREA_ID_KEY = "areaId";
	private static final String AREA_NAME_KEY = "地区名称";
	@Autowired
	private Dao dao;

	@Autowired
	private SqlTemplate sqlTemplate;
	@Autowired
	private AreaService areaService;
	private BaseDAOInterface<AreaPerform> areaPerformDAO;

	public void setAreaPerformDAO(BaseDAOInterface<AreaPerform> areaPerformDAO) {
		this.areaPerformDAO = areaPerformDAO;
	}

	@Autowired
	private UnitService unitService;

	private final Map<Integer, Integer> monthQuarterMap = new HashMap<Integer, Integer>() {
		{
			put(1, 1);
			put(2, 1);
			put(3, 1);
			put(4, 2);
			put(5, 2);
			put(6, 2);
			put(7, 3);
			put(8, 3);
			put(9, 3);
			put(10, 4);
			put(11, 4);
			put(12, 4);
		}
	};

	public String indicatorExcelExport(ReportIndicatorQueryVO queryVO) {
		ReportIndicaotrQueryGrid reportIndicators = queryReportIndicators(queryVO);
		List<Map<String, ?>> body = reportIndicators.body;
		Set<String> head = reportIndicators.head;
		if (body.size() > 0) {
			// 导入的报表信息
			Properties properties = new Properties();
			java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
			try {
				properties.load(inputstream);
			} catch (Exception ex) {
				logger.error("加载配置文件出错", ex);
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String saveFileName = String.valueOf(sdf.format(new Date())) + ".xls"; // 生成excel
			File file = new File(properties.getProperty("fileUploadPath").trim() + saveFileName); // 路径是存文件的路径
			Workbook wb = null;
			// int rowNum = 0;
			try {
				wb = new HSSFWorkbook();
				Sheet sheet = wb.createSheet();
				if (sheet != null) {
					Row row = sheet.createRow(0);
					int j = 0;
					for (String next : head) {
						Cell headCell = row.createCell(j);
						headCell.setCellValue(next);
						j++;
					}
					for (int i = 0; i < body.size(); i++) {
						Row createRow = sheet.createRow(i + 1);
						Map<String, ?> map = body.get(i);
						int k = 0;
						for (String next : head) {

							String object = map.get(next).toString();
							Cell headCell = createRow.createCell(k);
							headCell.setCellValue(object);
							k++;
						}
					}
				}
				FileOutputStream out = new FileOutputStream(file);
				wb.write(out);
				out.close();
				return file.getName();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("IO出错", e);
			}
		}
		return "errorTitle";
	}

	/**
	 * 查询报表指标
	 * 
	 * @param queryVO
	 * @return
	 */
	public DynamicReportVO queryReportIndicatorsNew(ReportIndicatorQueryVO queryVO, boolean export) {
		List<ReportTimeVO> queryTimes = getQueryTimes(queryVO);
		List<IndicatorInfo> queryIndicatorInfos = getQueryIndicators(queryVO);
		Filter filter = new Filter();

		filter.addRule(new FilterRule(FilterConstant.LIKE, "unitProper", "%2%"));

		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "3"));
		if (StringUtils.isNotBlank(queryVO.getAreaId())) {
			List<Area> list = new ArrayList<Area>();
			List<Area> areaList = areaService.findChildren(queryVO.getAreaId(), list);
			List<String> areaIds = new ArrayList<String>();
			areaIds.add(queryVO.getAreaId());
			for (Area area : areaList) {
				areaIds.add(area.getId());
			}
			filter.addRule(new FilterRule(FilterConstant.COLLECTION, "area.id", areaIds.toArray()));
		}
		Result result = unitService.queryUnits(filter, null);
		List<Unit> units = (List<Unit>) result.getOperationResult();
		List<Map<String, Object>> table = Lists.newArrayList();
		List<String> gridHeads = Lists.newArrayList();
		gridHeads.add(AREA_NAME_KEY);
		gridHeads.add("上报单位");
		gridHeads.add("指标名称");
		gridHeads.add("指标单位");
		for (ReportTimeVO reportTimeVO : queryTimes) {
			gridHeads.add(reportTimeVO.format());
		}

		boolean ishave = false;
		for (IndicatorInfo indicatorInfo : queryIndicatorInfos) {
			Cnd cnd = Cnd.where("id", "=", indicatorInfo.getId()).and("indicatorType", "=",
					indicatorInfo.getIndicatorType());
			indicatorInfo = dao.fetch(IndicatorInfo.class, cnd);

			for (Unit unit : units) {

				if (queryVO.getAreaId().equals(unit.getArea().getId())) {
					ishave = true;
				}

				Map<String, Object> row = Maps.newLinkedHashMap();
				row.put(AREA_ID_KEY, unit.getArea().getId());
				row.put(AREA_NAME_KEY, unit.getArea().getAreaName());
				row.put("上报单位", unit.getUnitName());
				row.put("指标名称", indicatorInfo.getName());
				row.put("指标单位", indicatorInfo.getUnit());

				for (ReportTimeVO reportTimeVO : queryTimes) {
					String indicatorVal = null;
					try {
						indicatorVal = queryReportIndicator(unit, indicatorInfo, reportTimeVO);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
						indicatorVal = "";
					}
					row.put(reportTimeVO.format(), indicatorVal);
				}

				table.add(row);
			}

		}
		if (!ishave) {
			Map<String, Object> row = Maps.newLinkedHashMap();
			row.put("id", 0);
			row.put(AREA_ID_KEY, queryVO.getAreaId());
			table.add(row);
		}

		//	 transformResult(flag, rii.indicatorMap, rii.rtis, table);
		DynamicReportVO resultReal = new DynamicReportVO();
		List<List<String>> headers = Lists.newArrayList();
		headers.add(gridHeads);
		resultReal.setHeaders(headers);
		if (export)
			resultReal.setBody(converHdataToGdata(table));
		else
			resultReal.setBody(table);
		return resultReal;

	}

	public void exportIndicatorExcel(DynamicReportVO report, OutputStream out) {
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("配置文件有误", ex);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String folder = String.valueOf(sdf.format(new Date()));
		// folder = String.valueOf(dirCount.getAndIncrement());

		String path = properties.getProperty("excelDownPath").trim() + folder; // 路径是存文件的路径

		try {
			File fileFolder = new File(path);
			if (!fileFolder.exists()) {
				fileFolder.mkdirs();
			}
			File file = new File(path + File.separator + sdf + ".xls");
			if (!file.exists()) {
				file.createNewFile();
			}

			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet createSheet = wb.createSheet();
			List<List<String>> headers = report.getHeaders();
			List<Map<String, Object>> bodyOld = report.getBody();
			if (!headers.isEmpty()) {
				// String[] array = head.toArray(new String[] {});
				Sheet sheet = wb.getSheetAt(0);
				if (sheet != null) {

					int rowIndex = 0;
					for (List<String> headerRow : headers) {
						int cellIndex = 0;
						org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowIndex);
						for (String header : headerRow) {
							//							if (!header.equals("showChcekBox")) {
							Cell headCell = row.createCell(cellIndex);
							headCell.setCellValue(header);
							cellIndex++;
							//							}
						}
						rowIndex++;
					}
					Filter filterArea = new Filter();
					filterArea.setOrder(FilterConstant.ASC);
					filterArea.setSortBy("areaSort");
					List<AreaPerform> careas = areaPerformDAO.find(AreaPerform.class, filterArea, null);
					LinkedHashSet<String> linkedHashSet = Sets.newLinkedHashSet();
					for (int j = 0; j < careas.size(); j++) {
						AreaPerform area = careas.get(j);
						String areaId = area.getId();
						linkedHashSet.add(areaId);
					}
					// 转为父子结构
					List<Map<String, Object>> body = new ArrayList<Map<String, Object>>();
					for (String areaId : linkedHashSet) {
						for (int j = 0; j < bodyOld.size(); j++) {
							Map<String, Object> map = bodyOld.get(j);
							String dataAreaId = (String) map.get(AREA_ID_KEY);
							if (dataAreaId.equals(areaId)) {
								body.add(map);
							}
						}
					}
					for (int j = 0; j < body.size(); j++) {
						Map<String, Object> map = body.get(j);
						org.apache.poi.ss.usermodel.Row rowBody = sheet.getRow(j + headers.size());
						if (rowBody == null) {
							sheet.createRow(j + headers.size());
							rowBody = sheet.getRow(j + headers.size());
							int x = 0;
							List<String> indicatorNames = headers.get(0);
							for (String header : indicatorNames) {
								//								if (!header.equals("showChcekBox")) {
								Cell bodyCell = rowBody.createCell(x);
								bodyCell.setCellValue((String) map.get(header));
								x++;
								//								}
							}
						}
					}

				}
			}
			wb.write(out);
		} catch (IOException e) {
			logger.error("Excel文件错误", e);
		}
	}

	/**
	 * 将数据转换为父子结构的数据
	 * 
	 * @param hd
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List<Map<String, Object>> converHdataToGdata(List<Map<String, Object>> hdata) {

		int index = 1;

		Set<String> uniqueAreaIds = getUniqueAreaIds(hdata);
		String rootAreaId = Sets.newTreeSet(uniqueAreaIds).first();

		Map<String, Area> uniqueArea = getUniqueArea(uniqueAreaIds);

		List<Map<String, Object>> pdataTemp = Lists.newArrayList();
		for (String areaId : uniqueAreaIds) {
			Map<String, Object> row = Maps.newHashMap();
			row.put(AREA_ID_KEY, areaId);
			Area area = uniqueArea.get(areaId);
			row.put(AREA_NAME_KEY, area.getAreaName());

			List<Object> children = Lists.newArrayList();
			for (Map<String, Object> d : hdata) {
				d.put("id", index++);
				String dataAreaId = (String) d.get(AREA_ID_KEY);

				if (dataAreaId.equals(areaId) && d.get(AREA_NAME_KEY) != null) {
					children.add(d);
				}
			}

			row.put("children", children);
			pdataTemp.add(row);

		}

		List<Map<String, Object>> pdata = Lists.newArrayList();

		for (Map<String, Object> row : pdataTemp) {
			row.put("id", index++);
			String areaId = (String) row.get(AREA_ID_KEY);
			Area area = uniqueArea.get(areaId);
			if (rootAreaId.equals(areaId)) {
				pdata.add(row);
			} else {

				for (Map<String, Object> row1 : pdataTemp) {
					row1.put("id", index++);
					String key = (String) row1.get(AREA_ID_KEY);
					if (key.equals(area.getParentId())) {
						List child = (List) row1.get("children");
						child.add(0, row);
						break;
					}
				}
			}
		}

		return pdata;
	}

	private Set<String> getUniqueAreaIds(List<Map<String, Object>> hdata) {
		Set<String> uniqueAreaIds = Sets.newLinkedHashSet();
		for (Map<String, Object> row : hdata) {
			String areaId = (String) row.get(AREA_ID_KEY);
			uniqueAreaIds.add(areaId);
		}
		return uniqueAreaIds;
	}

	private Map<String, Area> getUniqueArea(Set<String> areaIds) {
		Map<String, Area> areas = Maps.newLinkedHashMap();
		for (String areaId : areaIds) {
			Area area = areaService.queryAreaById(areaId);
			areas.put(areaId, area);
		}

		return areas;
	}

	/**
	 * 查询报表指标
	 * 
	 * @param queryVO
	 * @return
	 */
	public ReportIndicaotrQueryGrid queryReportIndicators(ReportIndicatorQueryVO queryVO) {
		List<ReportTimeVO> queryTimes = getQueryTimes(queryVO);
		List<IndicatorInfo> queryIndicatorInfos = getQueryIndicators(queryVO);

		List<Unit> units = unitService.queryUnitByAreaAndRole(queryVO.getAreaId(), queryVO.getUnitType());

		List<Map<String, ?>> table = Lists.newArrayList();
		Set<String> gridHeads = Sets.newLinkedHashSet();
		gridHeads.add("上报单位");
		gridHeads.add("指标名称");
		gridHeads.add("指标单位");

		for (IndicatorInfo indicatorInfo : queryIndicatorInfos) {
			Cnd cnd = Cnd.where("id", "=", indicatorInfo.getId()).and("indicatorType", "=",
					indicatorInfo.getIndicatorType());
			indicatorInfo = dao.fetch(IndicatorInfo.class, cnd);
			for (Unit unit : units) {
				Map<String, String> row = Maps.newLinkedHashMap();
				row.put("上报单位", unit.getUnitName());
				row.put("指标名称", indicatorInfo.getName());
				row.put("指标单位", indicatorInfo.getUnit());

				for (ReportTimeVO reportTimeVO : queryTimes) {
					String indicatorVal = null;
					try {
						indicatorVal = queryReportIndicator(unit, indicatorInfo, reportTimeVO);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
						indicatorVal = "";
					}
					row.put(reportTimeVO.format(), indicatorVal);
					gridHeads.add(reportTimeVO.format());
				}

				table.add(row);
			}
		}

		ReportIndicaotrQueryGrid grid = new ReportIndicaotrQueryGrid();
		grid.head = gridHeads;
		grid.body = table;
		return grid;

	}

	/**
	 * 查询单个指标值.
	 * 
	 * @param unit
	 * @param indicatorInfo
	 * @param reportTimeVO
	 * @return
	 */
	private String queryReportIndicator(Unit unit, IndicatorInfo indicatorInfo, ReportTimeVO reportTimeVO) {

		Map<String, Object> params = Maps.newHashMap();
		Map<String, Object> vars = Maps.newHashMap();

		addIndicatorParam(indicatorInfo, reportTimeVO.year, vars, params);

		// ReportTimeVO reportTimeVO = frequencyConverter(indicatorAccounting, reference, indicatorAccountVO);
		params.put("provinceUnitId", unitService.getProvinceOceanUnit().getId());
		params.put("reportTimetype", reportTimeVO.timeType);
		params.put("reportYear", reportTimeVO.year);
		String sql = "SELECT rd.$clomun ";
		// if (reference.getGetValueType() == GET_VALUE_TYPE_GET) {
		// sql += " rd.$clomun ";
		// } else {
		// sql += " SUM(rd.$clomun) ";
		// }
		sql += "FROM tbl_report r INNER JOIN tbl_report_detail rd ON r.id = rd.report_id "
				+ " INNER JOIN tbl_user u ON r.report_user_id = u.id "
				+ " INNER JOIN tbl_report_unit ru ON ru.report_id = r.id"
				//暂时去掉省级终审通过
				//				AND ru.operator_unit = @provinceUnitId AND ru.check_status = '5' "
				+ " WHERE r.report_type_id = @reportTypeId  ";

		if (params.containsKey("row")) {
			sql += " AND rd.row_index = @row ";
		}
		// 取值时，直接取对应的地区id报表数据
		sql += " AND u.user_unit = @unitId ";
		params.put("unitId", unit.getId());

		// 汇总时间频率条件SQL
		if (reportTimeVO.timeType == Constants.REPORT_TIME_MONTH) {
			sql += " AND r.report_timetype = @reportTimetype AND r.report_year = @reportYear AND r.month = @month ";
			params.put("month", reportTimeVO.month);
		} else if (reportTimeVO.timeType == Constants.REPORT_TIME_YEAR) {
			sql += " AND r.report_timetype = @reportTimetype AND r.report_year = @reportYear AND r.report_year_time = @reportYearTime ";
			params.put("reportYearTime", reportTimeVO.yearTime);
		} else {
			sql += " AND r.report_timetype = @reportTimetype AND r.report_year = @reportYear AND r.quarter = @quarter ";
			params.put("quarter", reportTimeVO.quarter);
		}

		// 引用指标值不存在，默认为空字符串
		String indicatorValue = null;
		try {
			indicatorValue = sqlTemplate.queryForObject(sql, vars, params, String.class);
			if (indicatorValue == null) {
				indicatorValue = "";
			}
		} catch (Exception e) {
			logger.error(
					String.format("查询指标错误，引用指标信息：统计制度代码: %d,指标id：%d,vars：%s,params：%s",
							indicatorInfo.getIndicatorType(), indicatorInfo.getId(), vars, params), e);
			indicatorValue = "";
		}
		return indicatorValue;
	}

	/**
	 * 增加指标所对应的报表参数,包括报表id，所在行列
	 * 
	 * @param reference
	 * @param params
	 */
	private void addIndicatorParam(IndicatorInfo indicatorInfo, int year, Map<String, Object> vars,
			Map<String, Object> params) {

		ReportTypeIndicator reportTypeIndicatorRel = queryReportTypeIndicatorRel(indicatorInfo.getIndicatorType(),
				indicatorInfo.getId(), year);

		if (reportTypeIndicatorRel == null) {
			logger.error("无法获取指标与报表的关系，引用指标信息：统计制度代码: {},指标id：{}", indicatorInfo.getIndicatorType(),
					indicatorInfo.getId());
			throw Lang.makeThrow("无法获取指标与报表的关系");
		} else {

			String reportTypeId = reportTypeIndicatorRel.getReportTypeId();
			Integer row = reportTypeIndicatorRel.getRow();
			Integer clomun = reportTypeIndicatorRel.getTheColumn();

			params.put("reportTypeId", reportTypeId);
			if (row != null) {
				params.put("row", row);
			}
			vars.put("clomun", "f" + clomun.intValue());
		}
	}

	/**
	 * 查询报表与指标的关系.
	 * 
	 * @param reportStatSystem 报表制度
	 * @param indicatorId 指标id
	 * @param year 查询年份
	 * @return
	 */
	private ReportTypeIndicator queryReportTypeIndicatorRel(int statSystem, Integer indicatorId, int year) {
		String sql = "SELECT rtip.* FROM t_report_type_indicator rtip INNER JOIN tbl_report_type rt ON rtip.report_type_id = rt.id "
				+ " INNER JOIN tbl_report_version rv "
				+ " ON rt.version_id = rv.id AND rv.start_date <= @year AND rv.end_date >= @year AND rv.stat_system = @statSystem "
				+ " WHERE rtip.indicator_id = @indicatorId ";
		Map<String, Object> params = Maps.newHashMap();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy");
		try {
			params.put("year", sd.parse(year+""));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		params.put("indicatorId", indicatorId);
		params.put("statSystem", statSystem);
		Entity<ReportTypeIndicator> entity = dao.getEntity(ReportTypeIndicator.class);
		return sqlTemplate.queryForObject(sql, params, entity);

	}

	/**
	 * 获得查询指标的信息
	 * 
	 * @param queryVO
	 * @return
	 */
	private List<IndicatorInfo> getQueryIndicators(ReportIndicatorQueryVO queryVO) {
		List<IndicatorInfo> indicators = Lists.newArrayList();

		for (String statSystemIndicatorStr : queryVO.getIndicators()) {
			String[] statSystemIndicatorIdArray = statSystemIndicatorStr.split("_");

			IndicatorInfo indicatorInfo = new IndicatorInfo();
			indicatorInfo.setIndicatorType(Integer.valueOf(statSystemIndicatorIdArray[0]));
			indicatorInfo.setId(Integer.valueOf(statSystemIndicatorIdArray[1]));
			indicators.add(indicatorInfo);
		}

		return indicators;
	}

	/**
	 * 获取两个时间范围内所有时间查询条件
	 * 
	 * @param queryVO
	 * @return
	 */
	private List<ReportTimeVO> getQueryTimes(ReportIndicatorQueryVO queryVO) {
		processReportIndicatorQueryEndTime(queryVO);

		List<ReportTimeVO> result = null;

		if (Constants.REPORT_TIME_YEAR == queryVO.getTimeType()) {
			result = getQueryYears(queryVO);
		} else if (Constants.REPORT_TIME_QUARTER == queryVO.getTimeType()) {
			result = getQueryQuarters(queryVO);
		} else {
			result = getQueryMonths(queryVO);
		}

		return result;
	}

	/**
	 * 处理查询终止时间,如果没设置终止时间，则将当前时间设置为终止时间.
	 * 
	 * @param queryVO
	 */
	private void processReportIndicatorQueryEndTime(ReportIndicatorQueryVO queryVO) {
		Calendar now = Calendar.getInstance();
		if (queryVO.getEndYear() == null || queryVO.getEndYear() == 0) {
			queryVO.setEndYear(now.get(Calendar.YEAR));
		}

		if (queryVO.getEndMonth() == null || queryVO.getEndMonth() == 0) {
			queryVO.setEndMonth(now.get(Calendar.YEAR) + 1);
		}

		if (queryVO.getEndQuarter() == null || queryVO.getEndQuarter() == 0) {
			int month = now.get(Calendar.YEAR) + 1;
			queryVO.setEndQuarter(monthQuarterMap.get(month));
		}

	}

	/**
	 * 获得查询的年份月份列表集合.
	 * 
	 * @param queryVO
	 * @return
	 */
	private List<ReportTimeVO> getQueryMonths(ReportIndicatorQueryVO queryVO) {
		int startYear = queryVO.getStartYear();
		int startMonth = queryVO.getStartMonth();

		int endYear = queryVO.getEndYear();
		int endMonth = queryVO.getEndMonth();

		List<ReportTimeVO> rts = Lists.newArrayList();
		int currentYear = startYear, currentMonth = startMonth;
		for (; currentYear <= endYear; currentYear++) {

			for (; currentMonth <= 12; currentMonth++) {
				if (currentYear == endYear && currentMonth > endMonth) {
					break;
				}
				ReportTimeVO rt = ReportTimeVO.createMonthTime(queryVO.getTimeType(), currentYear, currentMonth);
				rts.add(rt);
			}
			currentMonth = 1;
		}
		return rts;
	}

	/**
	 * 获得查询的年份季度列表集合.
	 * 
	 * @param queryVO
	 * @return
	 */
	private List<ReportTimeVO> getQueryQuarters(ReportIndicatorQueryVO queryVO) {
		int startYear = queryVO.getStartYear();
		int startQuarter = queryVO.getStartQuarter();

		int endYear = queryVO.getEndYear();
		int endQuarter = queryVO.getEndQuarter();

		List<ReportTimeVO> rts = Lists.newArrayList();
		int currentYear = startYear, currentQuarter = startQuarter;
		for (; currentYear <= endYear; currentYear++) {

			for (; currentQuarter <= 4; currentQuarter++) {
				if (currentYear == endYear && currentQuarter > endQuarter) {
					break;
				}
				ReportTimeVO rt = ReportTimeVO.createQuarterTime(queryVO.getTimeType(), currentYear, currentQuarter);
				rts.add(rt);
			}
			currentQuarter = 1;
		}
		return rts;
	}

	/**
	 * 获得查询的年份列表集合.
	 * 
	 * @param queryVO
	 * @return
	 */
	private List<ReportTimeVO> getQueryYears(ReportIndicatorQueryVO queryVO) {
		int startYear = queryVO.getStartYear();

		int endYear = queryVO.getEndYear();

		List<ReportTimeVO> rts = Lists.newArrayList();
		int currentYear = startYear;
		for (; currentYear <= endYear; currentYear++) {
			ReportTimeVO rt = ReportTimeVO.createYearTime(queryVO.getTimeType(), currentYear, queryVO.getYearTime());
			rts.add(rt);
		}
		return rts;
	}

	public static class ReportIndicaotrQueryGrid {

		Set<String> head;

		List<Map<String, ?>> body;

		public Set<String> getHead() {
			return head;
		}

		public List<Map<String, ?>> getBody() {
			return body;
		}

	}

	/**
	 * 报表时间值对象.
	 */
	static class ReportTimeVO {
		Integer timeType;
		Integer year;
		Integer yearTime;
		Integer quarter;
		Integer month;

		public ReportTimeVO(Integer timeType, Integer year, Integer yearTime, Integer quarter, Integer month) {
			this.timeType = timeType;
			this.year = year;
			this.yearTime = yearTime;
			this.quarter = quarter;
			this.month = month;
		}

		static ReportTimeVO createYearTime(Integer timeType, Integer year, Integer yearTime) {
			return new ReportTimeVO(timeType, year, yearTime, null, null);
		}

		static ReportTimeVO createQuarterTime(Integer timeType, Integer year, Integer quarter) {
			return new ReportTimeVO(timeType, year, null, quarter, null);
		}

		static ReportTimeVO createMonthTime(Integer timeType, Integer year, Integer month) {
			return new ReportTimeVO(timeType, year, null, null, month);
		}

		public String format() {
			String str = null;
			if (timeType == Constants.REPORT_TIME_YEAR) {
				if (yearTime == 1) {
					str = String.format("%d年 上半年", year);
				} else if (yearTime == 2) {
					str = String.format("%d年", year);
				} else {
					str = String.format("%d年", year);
				}
			} else if (timeType == Constants.REPORT_TIME_QUARTER) {
				str = String.format("%d年%d季度", year, quarter);
			} else {
				str = String.format("%d年%d月", year, month);
			}
			return str;
		}

	}
}
